# 1.找到未加密的参数
# 2.想办法把参数进行加密(参考网易云音乐逻辑加密) 参数列表[params,encSecKey] ==> 【params: bVi6c.encText , encSecKey: bVi6c.encSecKey】
# 3.请求到网页，拿到评论数据
import json

import requests

# 目标url = https://music.163.com/weapi/comment/resource/comments/get?csrf_token=
url = 'https://music.163.com/weapi/comment/resource/comments/get?csrf_token='
# 请求方式 => post
# json逆向 => 查看发起程序【由下往上方向调用】,程序员从顶部开始查看
# 网页加密方法 => window.asrsea(参数,xxxxx,xxx,xxx)

# 原数据
data = {
    "csrf_token": "",
    'cursor': "-1",
    'offset': "0",
    'orderType': "1",
    'pageNo': "1",
    'pageSize': "20",
    'rid': "A_PL_0_8510516438",
    'threadId': "A_PL_0_8510516438"
}

# 处理加密过程
'''
function a(a) { # 返回一个16的随机字符串
        var d, e, b = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", c = "";
        for (d = 0; a > d; d += 1)        # 循环16次
            e = Math.random() * b.length, # 根据b字符串长度获取随机数
            e = Math.floor(e),            # 取整
            c += b.charAt(e);             # 拼接在b字符串中获取的字符
        return c                          # 返回拼接的字符串
    }
    function b(a, b) { # a要加密的内容
        var c = CryptoJS.enc.Utf8.parse(b) # b是密钥
          , d = CryptoJS.enc.Utf8.parse("0102030405060708")
          , e = CryptoJS.enc.Utf8.parse(a) # e是数据
          , f = CryptoJS.AES.encrypt(e, c, { # c是加密的密钥
            iv: d, # 偏移量
            mode: CryptoJS.mode.CBC # 模式：CBC
        });
        return f.toString()
    }
    function c(a, b, c) {   # 如果参数a固定，则c返回一个固定值
        var d, e;
        return setMaxDigits(131),
        d = new RSAKeyPair(b,"",c),
        e = encryptedString(d, a)
    }
    # 重点
    function d(d, e, f, g) { 参数d：原数据 ，e:'010001'，f:很长的字符串，g:'0CoJUm6Qyw8W8jud'
        var h = {}                      # 空对象
          , i = a(16);                  # 获取一个16的随机字符串
        h.encText = b(d, g),            # d是数据，g是密钥
        h.encText = b(h.encText, i),    # 返回的是params
        h.encSecKey = c(i, e, f),       # 返回的是encSecKey  ==> c(一个16的随机字符串, '010001', 很长的字符串)
        return h
    }
    
    
    h.encText两次加密
    1. r1 = h.encText = b(d, g) 
    2. h.encText = b(r1, i)
'''

'''
var cxT9K = t0x.be0x;
    t0x.be0x = function(X0x, e0x) {
        var i0x = {}
          , e0x = NEJ.X({}, e0x)
          , mt3x = X0x.indexOf("?");
        if (window.GEnc && /(^|\.com)\/api/.test(X0x) && !(e0x.headers && e0x.headers[eu1x.AW6Q] == eu1x.Gc7V) && !e0x.noEnc) {
            if (mt3x != -1) {
                i0x = j0x.gP1x(X0x.substring(mt3x + 1));
                X0x = X0x.substring(0, mt3x)
            }
            if (e0x.query) {
                i0x = NEJ.X(i0x, j0x.fQ1x(e0x.query) ? j0x.gP1x(e0x.query) : e0x.query)
            }
            if (e0x.data) {
                i0x = NEJ.X(i0x, j0x.fQ1x(e0x.data) ? j0x.gP1x(e0x.data) : e0x.data)
            }
            i0x["csrf_token"] = t0x.gO1x("__csrf");
            X0x = X0x.replace("api", "weapi");
            e0x.method = "post";
            delete e0x.query;
            var bVi6c = window.asrsea(JSON.stringify(i0x), bse6Y(["流泪", "强"]), bse6Y(Qu1x.md), bse6Y(["爱心", "女孩", "惊恐", "大笑"]));
            e0x.data = j0x.cr1x({
                encSecKey: bVi6c.encSecKey
            })
        }
        var cdnHost = "y.music.163.com";
        var apiHost = "interface.music.163.com";
        if (location.host === cdnHost) {
            X0x = X0x.replace(cdnHost, apiHost);
            if (X0x.match(/^\/(we)?api/)) {
                X0x = "//" + apiHost + X0x
            }
            e0x.cookie = true
        }
        cxT9K(X0x, e0x)
'''

e = "010001"
f = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7'
g = '0CoJUm6Qyw8W8jud'
# i = "B92dbdPjM3vzrKDZ"
i = "da0phHh1mtMb6a1F"

def get_encSecKey():
    # return "d5a0c96951a5a95dc294053ff2965febbd50833b942e1b8bd5108281da60a0bb8a2206896d958a07409461bb6c1d0e73324517329ff728e7592534cb0936451edd96f1f825fa834b9043bf77784a8a666dca3c804858bc69d19716b452143be9c2052ac1ba83dcf1580c8617acd833486a4aa6f130e8e47d63a32495669cd872"
    return "43e43650d805faa6e375ed42054080d4d041b35e502db71e458e8a70573dd30d458e3bf202412269d35a5c04388b9462bccdd9230032d4d2cf06f50c30a0c4ea5242d02dee6822967606018bdb9e45e2089383885f08bc898256a8bba3eaa87b62deb1aba0cd86681df4735731e1a7cbfd548ce02fe9fa7ac9ea66410c03d42c"


def get_params(data):
    first = enc_params(data, g)
    second = enc_params(first, i)
    return second


def to_16(data):
    pad = 16 - len(data) % 16
    data += chr(pad)*pad
    return data

# 加密逻辑
def enc_params(data, key):
    # data必须为字符串
    from Crypto.Cipher import AES
    from base64 import b64encode

    aes = AES.new(key=key.encode('utf-8'),IV="0102030405060708".encode('utf-8'),mode=AES.MODE_CBC) # 创建加密器
    data2 = to_16(data)
    bs = aes.encrypt(data2.encode('utf-8')) # 加密.加密内容的长度必须为16的倍数
    return str(b64encode(bs),'utf-8')


resp = requests.post(url=url,data={
    "params":get_params(data=json.dumps(data)),
    'encSecKey':get_encSecKey()

})


# print("状态码：", resp.status_code)
# print("响应头：", resp.headers)
# print("响应内容：", resp.text)

print(resp.text)

print("----------------------")

respJs = json.loads(resp.text)
comments = respJs.get('data').get("comments")
for i in comments:
    user = i.get('user').get("nickname")
    msg = str(i.get('content')).strip().replace("\n","")
    print(user," : ",msg)